/*
2019年9月4日 星期三
ref_account 参照页面
 */

declare var $: any;
declare var weui: any;
declare var Wap: instance;

import {
    instance,
    Pager
} from '../../../src/Wap';

// link:  https://github.com/pqina/filepond
import * as FilePond from 'filepond';


// 系统全局性变量
(<any>window).Wap = instance;

(<any>$)(function () {
    /**
     * 默认购置页面
     */
    class App{
        _page: any;
        constructor(){
            this._page = new Pager();
            this._page = Wap.forwardTopScroll('#js__main');
            this._page.hide();
            this.listening();
        }

        /**
         * 监听
         */
        listening(){
            // 文件上传
            $('#account_upload').click(function () {
                console.log(Math.random());
            });
            /*
            // submit-btn，表单提交
            $('#submit-btn').click(function () {
                let loading = instance.weuiLoading('数据提交中……');
                //@todo 待实现ajax文件上传实现，csv文件导入
                //link: https://www.cnblogs.com/Renyi-Fan/p/9581951.html
                weui.form.validate('.js__form', function (error) {
                    if (!error) {
                        let savedata = Wap.formJson('.js__form'),
                            file = $('#csv_refdata').prop('files'),
                            reg = /\.csv$/
                        ;
                        if(!reg.test(file[0].name)){
                            loading.hide();
                            weui.topTips('上传文件必须为 CSV 格式');
                            return false;
                        }

                        savedata.csv = file[0];
                        let pdata = new FormData();
                        pdata.append('ref_type', savedata.ref_type);
                        pdata.append('csv', file[0]);
                        console.log(pdata, savedata);
                        //console.log(savedata, file);
                        Wap.ApiRequest('ref_account/csv',pdata,function (data) {
                            loading.hide();
                        });
                    }else{
                        loading.hide();
                    }
                });
            });
            */
           /* $("#csv_refdata").liteUploader({
                url: instance.ApiUrl('ref_account/csv')
            })
            .on("lu:success", function (e, {response}) {
                console.log(response);
            })
            .on("lu:cancelled", function () {
                console.log("upload aborted");
            })
            ;*/

            this._filePond();

            // 提交表单内容
            $('#submit-btn').click(function () {
                var loading = instance.weuiLoading('数据提交中……');
                weui.form.validate('.js__form', function (error) {
                    console.log(error);
                    let savedata = Wap.formJson('.js__form');
                    if(!error){
                        Wap.ApiRequest('ref_account/csv',savedata,function (rs) {
                            loading.hide();
                            console.log(rs);
                        });
                    }else{
                        loading.hide();
                        if(!savedata.file_hash){
                            weui.topTips('请先选择上传文件！');
                        }
                        console.log(savedata);
                    }
                });
            });

        }

        /**
         * 文件上传插件
         * @private
         */
        _filePond(){
            FilePond.setOptions({
                server: instance.ApiUrl('ref_account/csv_upload')
            });
            // Create a multi file upload component
            const attr = {
                multiple: false,
                name: 'filepond'
            };
            const pond = FilePond.create(<any>attr);
            // 单文件
            pond.setOptions({
                maxFiles: 1,
                required: true
            });
            // Add it to the DOM
            //document.body.appendChild(pond.element);
            $('#file_upload').html(pond.element);
            let error = (er) => {
                throw new Error(er);
            };
            // 文件添加
            pond.on('addfile', (er, fl) => {
                $('#file_hash_id').val('');
                if(er){
                    //error(er);
                    console.log(er);
                    pond.removeFile();
                    return false;
                }
                /*
                let refType = $('[name="ref_type"]:checked').val();
                if(!refType){
                    weui.topTips('请先选择类型');
                    error('文件上传错误');
                    pond.removeFile();
                    return false;
                }
                 */
                let serverId = fl.file.serverId;
                console.log(serverId);
                if (serverId){
                    serverId = JSON.parse(serverId);
                    console.log(serverId);
                }
                console.log(fl, 85);
                console.log(fl.serverId);
            });

            // 文件上传
            pond.on('processfile', (er, fl) => {
                if (er){
                    console.log(er);
                    return false;
                }
                let serverId = fl.serverId;
                if (serverId){
                    serverId = JSON.parse(serverId);
                    if (serverId.code == 1){
                        $('#file_hash_id').val(serverId.data.hash);
                    }else {
                        weui.topTips(serverId.msg);
                    }
                }
            });
            // 插件监听
            pond.on('addfilestart', e => {
                let refType = $('[name="ref_type"]:checked').val();
                pond.getFile().setMetadata('ref_type',  refType);
            });
        }
    }

    new App();
});